package com.ruoyi.web.controller.backstage;

import com.ruoyi.system.service.ISysFileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * @author Administrator
 */
@RequestMapping("/image")
@Controller
public class SysImageController {

    @Autowired
    private ISysFileInfoService sysFileInfoService;
    /**
     * 获取文件信息详细信息
     */
    @GetMapping(value = "/{fileId}")
    @ResponseBody
    public void getInfo(@PathVariable("fileId") String fileId, HttpServletRequest request, HttpServletResponse response)
    {
        String url = sysFileInfoService.selectSysFilePathById(fileId);
        try {
            if (url != null) {
                URL urlImg = new URL(url);
                //创建链接对象
                URLConnection urlConnection = urlImg.openConnection();
                //设置超时
                urlConnection.setConnectTimeout(1000);
                urlConnection.setReadTimeout(5000);
                urlConnection.connect();
                //获取流
                InputStream inputStream = urlConnection.getInputStream();
                //读取图片
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                if (bufferedImage != null) {
                    //获取图片格式
                    String format = url.substring(url.lastIndexOf(".") + 1);
                    //打印图片
                    // 将文件流放入response中
                    response.setContentType("image/gif");
                    ImageIO.write(bufferedImage, format, response.getOutputStream());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
